package forum.service.rpc;

import com.alibaba.druid.util.StringUtils;
import com.foreveross.springboot.dubbo.utils.BeanHelper;
import forum.domain.PageDto;
import forum.domain.Resources;
import forum.repository.ResourcesRepository;
import forum.service.rpc.api.ResourcesService;
import forum.service.tools.BaseSearch;
import forum.service.tools.SearchDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.ws.rs.DefaultValue;
import javax.ws.rs.QueryParam;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by Administrator on 2017/4/5.
 */
@Service("resourcesService")
public class ResourcesServiceImpl implements ResourcesService {

    @Autowired
    private ResourcesRepository resourcesRepository;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public Object getResourcesList(@QueryParam("page") @DefaultValue("0") int page,
                                   @QueryParam("size") @DefaultValue("50") int size,
                                   @QueryParam("sort") @DefaultValue("sort=roleid,desc") String sort,
                                   @QueryParam("operation") @DefaultValue("operation=eq") String operation,
                                   @QueryParam("key") @DefaultValue("key=roleid") String key,
                                   @QueryParam("value") @DefaultValue("1") String value) {
//        logger.debug("get roles: {} . -> {}", "GET /api/v1/roles/", sort);

        // 简单适配, 暂无严谨性
        sort = sort.replaceAll("sort=", "").trim(); // sort=firstname,desc
        String[] sort_arr = sort.split(",");
        Sort.Direction direction;
        if (sort_arr[1] != null && "desc".equals(sort_arr[1])) {
            direction = Sort.Direction.DESC;
        } else {
            direction = Sort.Direction.ASC;
        }
        String[] properties = sort_arr[0].split("&");

        Sort _sort = new Sort(direction, Arrays.asList(properties));
        Pageable pageable = new PageRequest(page, size, _sort);

        if(StringUtils.isEmpty(key) || StringUtils.isEmpty(operation)  || StringUtils.isEmpty(value)){
            logger.info("提示: key或者operation或者value为空 ");

        }

        if(!StringUtils.isEmpty(key) && !StringUtils.isEmpty(operation)  && !StringUtils.isEmpty(value)){
            logger.info("提示: key并且operation并且value都不为空 ");
            List<Resources> list = new ArrayList<Resources>();
            PageDto pageDto =new PageDto();
            list = resourcesRepository.findAll(new BaseSearch<Resources>(new SearchDto(key,operation, value)),pageable).getContent();
            for(Resources resources : list){
                List<Resources> children =  resourcesRepository.findByParentid(resources.getResourcesid());
                resources.setChildren(children);
            }
            return list;
        }

        return  resourcesRepository.findAll(pageable);

    }

    @Override
    public Object getResourcesById(Integer id) {
        Resources resources = resourcesRepository.findOne(id);
        if(resources==null){
            return "id = " + id + " 资源不存在";
        }
        if(resources.getParentid()==0){
            List<Resources> children =  resourcesRepository.findByParentid(resources.getResourcesid());
            for(Resources resourceschildren : children){
                resources.setChildren(children);
            }
            return resources;
        }else{
            return resources;
        }

    }

    @Override
    public Object createResources(Resources resources) {
        if (resources != null) {
            List<Resources> list =  resourcesRepository.findByResourcesname(resources.getResourcesname());
            if (list != null && list.size() != 0 && resources.getParentid() == 0){
                    return resources.getResourcesname() + " 菜单资源已经被存在！";
            }
            resourcesRepository.save(resources);
        }
        return resources;
    }

    @Override
    public Object updateResourcesById(Resources resources) {
        Resources _resources = null;
        Resources parent_resources = null;
        if(resources.getParentid() > 0 && resources != null && resources.getResourcesid() > 0 && resources.getResourcesid()!=null){
            _resources = resourcesRepository.findOne(resources.getResourcesid());
            parent_resources = resourcesRepository.findOne(resources.getParentid());
            if(_resources!=null){
                if(parent_resources == null){
                    return "父菜单的资源ID不存在";
                }else{
                    BeanHelper.mapPartOverrider(_resources, resources);
                    resourcesRepository.save(_resources);
                }
            }else {
                return "ID资源不存在";
            }

        }
        return _resources;
    }

    @Override
    @Transactional
    public Object deleteResourcesByIds(Integer[] resourcesIds) {
        boolean flag = false;
        if (resourcesIds != null && resourcesIds.length > 0) {
            for (int i=0;i<resourcesIds.length;i++){
              Resources resources =  resourcesRepository.findOne(resourcesIds[i]);
              if (resources==null){
                  return flag;
              }else if(resources.getParentid()==0){//父级菜单
                  resourcesRepository.delete(resourcesIds[i]);//删除父级菜单的资源
                  resourcesRepository.deleteByResourcesid(resourcesIds[i]);//删除父级菜单资源的角色资源关联表
                  List<Resources> _resources = resourcesRepository.findByParentid(resourcesIds[i]);
                  if(_resources.size()>0 && _resources!=null){
                      for(Resources resources1 : _resources){
                          resourcesRepository.delete(resources1.getResourcesid());//删除子级菜单的资源
                          resourcesRepository.deleteByResourcesid(resources1.getResourcesid());  //删除子级菜单的资源角色资源关联表
                      }
                  }
                  flag = true;
              }else{
                  resourcesRepository.delete(resourcesIds[i]);
                  resourcesRepository.deleteByResourcesid(resourcesIds[i]);
                  flag = true;
              }
            }
        }
        return flag;
    }
}
